#include"BTree.hpp"

BTNode* BuyBTNode(BTDataType x)
{
    BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
    assert(newnode);

    newnode->left = NULL;
    newnode->right = NULL;
    newnode->data = x;

    return newnode;
}


//创建二叉树
BTNode* CreateBTree()
{
    BTNode* node1 = BuyBTNode(1);
    BTNode* node2 = BuyBTNode(2);
    BTNode* node3 = BuyBTNode(3);
    BTNode* node4 = BuyBTNode(4);
    BTNode* node5 = BuyBTNode(5);
    BTNode* node6 = BuyBTNode(6);

    node1->left = node2;
    node1->right = node3;
    node2->left = node4;
    node3->left = node5;
    node3->right = node6;

    return node1;
}

//前序遍历
void PrevOrder(BTNode* root)
{
    if(root == NULL)
    {
        return;
    }

    printf("%d ", root->data);
    PrevOrder(root->left);
    PrevOrder(root->right);
}

//中序遍历
void InOrder(BTNode* root)
{
    if(root == NULL)
    {
        return;
    }

    InOrder(root->left);
    printf("%d ", root->data);
    InOrder(root->right);
}

//后序遍历
void PostOrder(BTNode* root)
{
    if(root == NULL)
    {
        return;
    }

    PostOrder(root->left);
    PostOrder(root->right);
    printf("%d ", root->data);
}

//节点总数
int BTreeSize(BTNode* root)
{
    if(root == NULL)
        return 0;

    return BTreeSize(root->left) + BTreeSize(root->right) + 1;
}


//叶子总数
int BTreeLeafSize(BTNode* root)
{
    if(root == NULL)
        return 0;

    if(root->left == NULL && root->right == NULL)
        return 1;

    return BTreeLeafSize(root->left) + BTreeLeafSize(root->right);
}


//第K层节点的个数
int BTreeKLevelSize(BTNode* root, int k)
{
    assert(k >= 1);

    //空树
    if(root == NULL)
        return 0;

    //非空
    if(k == 1)
        return 1;

    return BTreeKLevelSize(root->left, k - 1) + BTreeKLevelSize(root->right, k - 1);
}









int main()
{
    BTNode* root = CreateBTree();

    PrevOrder(root);
    printf("\n");

    InOrder(root);
    printf("\n");

    PostOrder(root);
    printf("\n");

    
    printf("节点个数       :  %d\n", BTreeSize(root));
    printf("叶子个数       :  %d\n", BTreeLeafSize(root));
    printf("第K层节点个数  :  %d\n", BTreeKLevelSize(root, 3));

    return 0;
}